package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import com.ibm.icu.text.SimpleDateFormat;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/3/19 11:11
 */
public class DwmUvApp extends BaseAppV1 {
    public static void main(String[] args) {
        new DwmUvApp().init(3001,
                            1,
                            "DwmUvApp",
                            "DwmUvApp",
                            Constant.TOPIC_DWD_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private SimpleDateFormat sdf;
                private ValueState<String> dateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    dateState = getRuntimeContext().getState(
                        new ValueStateDescriptor<String>("dateState", String.class));
                    
                    sdf = new SimpleDateFormat("yyyy-MM-dd ");
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    String yesterday = dateState.value();
                    String today = sdf.format(ctx.window().getStart());
    
                    if (!today.equals(yesterday)) {
                        // 今天和昨天不一样, 跨天
                        dateState.clear();
                    }
    
    
                    if (dateState.value() == null) {
                        // 表示第一个窗口
                        // 只有第一个窗口才有必要把Iterable转成List, 其他的窗口, 可以直接忽略
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        /*Collections.min(list, new Comparator<JSONObject>(){
                            @Override
                            public int compare(JSONObject o1, JSONObject o2) {
                                return o1.getLong("ts").compareTo(o2.getLong("ts"));
                            }
                        });*/
                        //                        Collections.min(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        out.collect(min);
                        
                        // 更新状态  年月日
                        dateState.update(sdf.format(min.getLong("ts")));
                    }
                    
                    
                }
            })
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_UV));
    }
}
/*
为了dws层计算uv值, 做提前处理: 去重

dau 日活
1. 数据源? 选择 dwd_page
    kafka的dwd层的日志相关的数据
    
    dwd_start
        计算uv可以的, 但是得到的结果可能偏小
        启动日志只有使用app访问的时候才会有
        如果是使用浏览器访问, 则没有启动日志
        
    dwd_page
        使用今天的第一个页面用来计算uv
    
   
    dwd_display

2. uv实现逻辑?
 去重
 
  使用flink的状态
  
  使用窗口 + 事件时间
  
  考虑跨天的问题

 */